import React from 'react';
import DB from 'common/db';
import { Card, InputItem, Icon, Toast } from 'antd-mobile';
import CustomIcon from './Icon';
import TimeRange from './TimeRange';

const CompleteBtn = ({clickHandle}) => {
  return <div onClick={clickHandle}><Icon type='check'/></div>
} 

const DeleteBtn = ({clickHandle}) => {
  return <div onClick={clickHandle}><CustomIcon type='delete'/></div>
}


class ItemCard extends React.Component {
  constructor(props){
    super(props);
    this.db = window.hornDB;
  }

  /**
   * 更新时间（子组件调用）
   * @param {时间} time
   * @param {开始或结束时间} type ture : 开始时间
   */
  updateTimeRange = (time, type) => {
    const { timeRange } = this.props;
    if (type) {
      timeRange.start = time;
    } else {
      timeRange.end = time;
    }
    const data = {...this.props, timeRange};
    this.db.updateRx(data);
  }

  /**
   * 完成指定条目
   */
  completeItem = () => {
    const { id, content, timeRange: {start} } = this.props;
    const end = Date.now();
    const data = {
      id,
      state: 2,
      timeRange: {
        start,
        end,
      },
      content,
    };
    this.db.updateRx(data);
  }
  
  /**
   * 删除该条目
   */
  deleteItem = () => {
    const { id } = this.props;
    this.db.deleteRx(id);
  }


  render() {
    const { state, timeRange, content } = this.props;

    let Btn;
    let clickHandle;
    switch(state) {
      case 0:
      default:
        Btn = AddBtn;
        clickHandle = this.addItem;
        break;
      case 1:
        Btn = CompleteBtn;
        clickHandle = this.completeItem;
        break;
      case 2:
        Btn = DeleteBtn;
        clickHandle = this.deleteItem;
    }

    return <Card full style={{margin: '5px 0'}}>
    <Card.Header 
      title={<TimeRange {...timeRange} update={this.updateTimeRange}/>}
      extra={<Btn clickHandle={clickHandle}/>}/>
    <Card.Body>
      <InputItem
        value={content}
        onChange={this.changeContent}
        placeholder="添加一个条目"/>
    </Card.Body>
  </Card>
  }
}

export default ItemCard;
